import { NextRequest, NextResponse } from "next/server";
import { SqliteDatabase } from "@/lib/sqlite-database";

export async function GET(request: NextRequest) {
  try {
    const database = new SqliteDatabase();
    
    // 获取所有设备
    const allDevices = database.getAllDevices();
    console.log(`总设备数量: ${allDevices.length}`);
    
    // 详细分析每个参数表的数据分布
    const parameterAnalysis = {
      naming: {
        totalRecords: 0,
        deviceCoverage: [] as number[],
        missingDevices: [] as number[],
        sampleData: [] as any[]
      },
      position: {
        totalRecords: 0,
        deviceCoverage: [] as number[],
        missingDevices: [] as number[],
        sampleData: [] as any[]
      },
      base: {
        totalRecords: 0,
        deviceCoverage: [] as number[],
        missingDevices: [] as number[],
        sampleData: [] as any[]
      }
    };
    
    // 获取每种参数的设备覆盖情况
    for (const device of allDevices) {
      const deviceId = device.id!;
      
      // 检查命名参数
      const namingParams = database.getNamingParametersByDeviceId(deviceId);
      if (namingParams.length > 0) {
        parameterAnalysis.naming.deviceCoverage.push(deviceId);
        parameterAnalysis.naming.totalRecords += namingParams.length;
        // 只保存前3个设备的样本数据
        if (parameterAnalysis.naming.sampleData.length < 3) {
          parameterAnalysis.naming.sampleData.push({
            deviceId,
            deviceName: device.name,
            parameterCount: namingParams.length,
            firstFewParams: namingParams.slice(0, 3).map(p => p.parameter_name)
          });
        }
      } else {
        parameterAnalysis.naming.missingDevices.push(deviceId);
      }
      
      // 检查位置参数
      const positionParams = database.getPositionParametersByDeviceId(deviceId);
      if (positionParams.length > 0) {
        parameterAnalysis.position.deviceCoverage.push(deviceId);
        parameterAnalysis.position.totalRecords += positionParams.length;
        if (parameterAnalysis.position.sampleData.length < 3) {
          parameterAnalysis.position.sampleData.push({
            deviceId,
            deviceName: device.name,
            parameterCount: positionParams.length,
            firstFewParams: positionParams.slice(0, 3).map(p => p.parameter_name)
          });
        }
      } else {
        parameterAnalysis.position.missingDevices.push(deviceId);
      }
      
      // 检查基础参数
      const baseParams = database.getBaseParametersByDeviceId(deviceId);
      if (baseParams.length > 0) {
        parameterAnalysis.base.deviceCoverage.push(deviceId);
        parameterAnalysis.base.totalRecords += baseParams.length;
        if (parameterAnalysis.base.sampleData.length < 3) {
          parameterAnalysis.base.sampleData.push({
            deviceId,
            deviceName: device.name,
            parameterCount: baseParams.length,
            firstFewParams: baseParams.slice(0, 3).map(p => p.parameter_name)
          });
        }
      } else {
        parameterAnalysis.base.missingDevices.push(deviceId);
      }
    }
    
    // 计算范围信息
    const getRangeInfo = (deviceIds: number[]) => {
      if (deviceIds.length === 0) return { min: null, max: null, gaps: [] };
      
      const sorted = [...deviceIds].sort((a, b) => a - b);
      const gaps = [];
      
      for (let i = sorted[0]; i <= sorted[sorted.length - 1]; i++) {
        if (!sorted.includes(i)) {
          gaps.push(i);
        }
      }
      
      return {
        min: sorted[0],
        max: sorted[sorted.length - 1],
        gaps: gaps.slice(0, 10) // 只显示前10个缺口
      };
    };
    
    const summary = {
      totalDevices: allDevices.length,
      deviceIdRange: {
        min: Math.min(...allDevices.map(d => d.id!)),
        max: Math.max(...allDevices.map(d => d.id!))
      },
      parameterStats: {
        naming: {
          ...parameterAnalysis.naming,
          coverage: `${parameterAnalysis.naming.deviceCoverage.length}/${allDevices.length}`,
          range: getRangeInfo(parameterAnalysis.naming.deviceCoverage),
          missingCount: parameterAnalysis.naming.missingDevices.length
        },
        position: {
          ...parameterAnalysis.position,
          coverage: `${parameterAnalysis.position.deviceCoverage.length}/${allDevices.length}`,
          range: getRangeInfo(parameterAnalysis.position.deviceCoverage),
          missingCount: parameterAnalysis.position.missingDevices.length
        },
        base: {
          ...parameterAnalysis.base,
          coverage: `${parameterAnalysis.base.deviceCoverage.length}/${allDevices.length}`,
          range: getRangeInfo(parameterAnalysis.base.deviceCoverage),
          missingCount: parameterAnalysis.base.missingDevices.length
        }
      }
    };
    
    // 添加一些设备样本信息
    const deviceSamples = allDevices.slice(0, 5).map(device => ({
      id: device.id,
      deviceId: device.device_id,
      name: device.name,
      specialty: device.specialty,
      hasNaming: parameterAnalysis.naming.deviceCoverage.includes(device.id!),
      hasPosition: parameterAnalysis.position.deviceCoverage.includes(device.id!),
      hasBase: parameterAnalysis.base.deviceCoverage.includes(device.id!)
    }));
    
    return NextResponse.json({
      success: true,
      timestamp: new Date().toISOString(),
      summary,
      deviceSamples,
      recommendations: [
        parameterAnalysis.naming.missingDevices.length > 0 ? `发现 ${parameterAnalysis.naming.missingDevices.length} 个设备缺少命名参数` : "所有设备都有命名参数",
        parameterAnalysis.position.missingDevices.length > 0 ? `发现 ${parameterAnalysis.position.missingDevices.length} 个设备缺少位置参数` : "所有设备都有位置参数",
        parameterAnalysis.base.missingDevices.length > 0 ? `发现 ${parameterAnalysis.base.missingDevices.length} 个设备缺少基础参数` : "所有设备都有基础参数"
      ].filter(Boolean)
    });
    
  } catch (error) {
    console.error("诊断参数数据时出错:", error);
    return NextResponse.json(
      { 
        success: false, 
        message: "诊断参数数据过程中发生错误",
        error: error instanceof Error ? error.message : "未知错误"
      },
      { status: 500 }
    );
  }
} 